<?php
/**
 *  class for compiling content
 *
 * @package compile_text
 * @version 1.0
 * @copyright Copyright Urs Lang
 * @license BSD License (http://www.opensource.org/licenses/bsd-license)
 * 
 * 
 * 
 * 
 */

class compile_text
    {

// gibt <a ein problem????? (bei event manuell drin)
// bei <a gibts das Problem, dass innerhalb eines Linkes ebenfalls eine Tabelle erstellt wird (z.B. href="data_delete")

    public $header = "";
    public $controller = "";

    public $jsHeader = array();
    public $cssHeader = array();

    public $pageTitle = "";
    public $pageUrl = "";

    public $pageTemplate = "";
    public $pageId = 0;
    public $codeFilename;

    public $phpScriptPath;         // = "/code/php_script";
    public $systemPath = "../../"; //


    /**
    * Pfad in welchem sich das Orginal File befindet (für die Umwandlung von img, script, css etc.)
    */
    public $contentPath = "";

    public $compileModus =
        "content"; // mögliche werte: content, template, template_mobile (für die Umwandlung von img, script, css etc.)

    public $sourcePath = "";
    public $sourceUrl = "";

    public $imageRedirect = "";
    //public $distrubtionPath;

    // public $dom;
    //public $dataCom=new data();

    public $queryCounter = 0;
    public $phpScriptCounter = 0;
    public $jsScriptCounter = 0;

    public $compileTable = "template";
    public $compileField = "template2";

    // Pfad f?r Inclusions  Css, Php und Js Inlclusion Files
    public $preIncludePath = "";

    public $compileId = 0;

    private $arrayCom = array();
    private $arrayComAttribute = array();

    //private $developerModus;
    private $resetCounter = 0;

    private $phpReplaceFrom = array();
    private $phpReplaceTo = array();
    private $phpReplaceCounter = 0;

    private $attributeList = array();

    function __construct() { require_once(config::$basePath . "/system/api/simplehtmldom/simple_html_dom.php"); }

    function compileText($html)
        {

        // jQuery einfügen --> gibt Probleme, da es auch im Template integriert wird
        //$this->jsHeader[] = "/api/jquery/jquery.js";

        $this->propertyList=array();


        // Umwandlung [content:...]
        $html=str_ireplace("[content:title]", "[content_title:]", $html);
        $html=str_ireplace("[content:text]", "[content_edit:]", $html);


        //replaceAllEntities

        // Bug im Html Parser!!!!
        if ($html == "")
            {
            $html=" ";
            }

        $dom=str_get_html($html);

        //print_r($dom);

        //echo "html=".$html;
        //$html = "asdfasdfasdfasd";


        // replace File Extension in Forms
        $domArray=$dom->find("form");

        foreach ($domArray as $item)
            {
            if (isset($item->action))
                {

                //$link=$item->action;
                $filename=$item->action;
                // alles nach dem ? abschneiden, da es für die File Exist Abfrage nicht verwendet werden darf
                $filenameParameter=strstr($filename, "?");

                if ($filenameParameter !== false)
                    {
                    $filename=str_replace($filenameParameter, "", $filename);
                    }


                //if (file::fileExists(config::$projectPath . "/content/" . $item->action, false))
                if (file::fileExists(config::$projectPath . "/content/" . $filename, false))
                    {
                    $item->action=str_ireplace(".html", "", $item->action);
                    $item->action=str_ireplace(".htm", "", $item->action);
                    $item->action=str_ireplace(".php", "", $item->action);
                    //$item->action=$link;
                    }
                }


            // Redirect Hidden Input Field --> muss nach replace com ausgeführt werden, wegen form_scaffolding
            /*$htmlForm=
                '<input type="hidden" name="http_redirect" id="http_redirect" value="<?php if (isset($_REQUEST["http_redirect"])) { echo $_REQUEST["http_redirect"];}?>" />';
            $item->innertext=$item->innertext . $htmlForm;*/
            }

        $domArray=$dom->find("a");

        foreach ($domArray as $item)
            {
            if (isset($item->href))
                {

                //$link=$item->href;

                $filename=$item->href;
                // alles nach dem ? abschneiden, da es für die File Exist Abfrage nicht verwendet werden darf
                $filenameParameter=strstr($filename, "?");

                if ($filenameParameter !== false)
                    {
                    $filename=str_replace($filenameParameter, "", $filename);
                    }


                //$item->href
                if (file::fileExists(config::$projectPath . "/content/" . $filename, false))
                    {
                    $item->href=str_ireplace(".html", "", $item->href);
                    $item->href=str_ireplace(".htm", "", $item->href);
                    $item->href=str_ireplace(".php", "", $item->href);
                    }


                // falls kein Menu
                /* if ($link !== "[menu.url]") {
                     
                     // falls kein gültige Url
                     if (!check::isUrl($link))
                         $link = '<?php echo config::$baseUrl;?>'.$link;      
                     }   */

                //$item->href=$link;
                }
            }


        // problem, com in script und form sind nicht mehr aktuell
        // Dom basierte Ersetzungen

        //$dom=$this->replaceHref($dom);  --> alles in replacecom!!!!
        //$dom=$this->replaceForm($dom);
        $dom=$this->replaceCom($dom);
        
        
        
        
        
        
        
        
        // add http_redirect field
        $domArray=$dom->find("form");

        foreach ($domArray as $item)
            {
            // Redirect Hidden Input Field --> muss nach replace com ausgeführt werden, wegen form_scaffolding
            $htmlForm=
                '<input type="hidden" name="http_redirect" id="http_redirect" value="<?php if (isset($_REQUEST["http_redirect"])) { echo $_REQUEST["http_redirect"];}?>" />';
            $item->innertext=$item->innertext . $htmlForm;
            }
        
        
        
        
        
        
        
        
        
        $dom=$this->replaceAttribute($dom);
        $dom=$this->replaceEvent($dom);


        // eMail Adressen kodieren
        $dom=$this->replaceMailAdress($dom);


        // replace images, styles, js (was sonst noch?????)
        // problem: images in css styles!!!!!!!!!
        // problem flash

        $domArray=$dom->find("img");

        foreach ($domArray as $item)
            {
            if (isset($item->src))
                {
                $source=$item->src;

                switch ($this->compileModus)
                    {


                    // befindet sich die Datei im Content Ordner
                    case "content":
                        if (file::fileExists(config::$projectPath . "/content/" . $source, true))
                            {
                            $source='<?php echo config::$baseUrl.config::$projectPath."/content/";?>' . $source;
                            }

                        break;

                    //echo config::$projectPath."/data/template/".$source;
                    //exit;

                    // befindet sich die Datei im Template Ordner
                    case "template":
                        if (file::fileExists(config::$projectPath . config::$templatePath . "/" . $source, true))
                            {
                            $source='<?php echo config::$baseUrl.config::$projectPath."' . config::$templatePath
                                . '/";?>' . $source;
                            }

                        break;

                    // befindet sich die Datei im Template Mobile Ordner
                    case "template_mobile":
                        if (file::fileExists(config::$projectPath . "/template_mobile/" . $source, true))
                            {
                            $source='<?php echo config::$baseUrl.config::$projectPath."/template_mobile/";?>' . $source;
                            }

                        break;
                    }

                $item->src=$source;
                }
            }


        // replace File Extension in Hyperlinks
        // muss ersetzt werden, bevor com script eingefügt werden, WARUM --> gibt Probleme mit com script (delete_data)
        $domArray=$dom->find("a");

        foreach ($domArray as $item)
            {
            if (isset($item->href))
                {

                $link=$item->href;
                /*$link=str_ireplace(".html", "", $link);
                $link=str_ireplace(".htm", "", $link);
                $link=str_ireplace(".php", "", $link);    */


                // falls kein Menu
                if ($link !== "[menu.url]")
                    {

                    // falls kein gültige Url
                    if (!check::isUrl($link))

                        // befindet sich die Datei im Content Ordner
                        if (file::fileExists(config::$projectPath . "/content/" . $link, true))
                            {
                            $link='<?php echo config::$baseUrl;?>' . config::$projectPath . '/content/' . $link;
                            }


                    // befindet sich die Datei im Template Ordner
                    if (file::fileExists(config::$projectPath . "/template/" . $link, true))
                        {
                        $link='<?php echo config::$baseUrl;?>' . config::$projectPath . '/template/' . $link;
                        }


                    // falls Home Link
                    if ($link == "/")
                        {
                        $link='<?php echo config::$baseUrl;?>' . $link;
                        }


                    /*$link='<?php echo config::$baseUrl;?>' . $link;*/
                    }

                $item->href=$link;
                }
            }


        // ändern der Form's
        $domArray=$dom->find("form");

        foreach ($domArray as $item)
            {
            if (isset($item->action))
                {

                // falls kein gültige Url, anfügen der Template Url
                if (!check::isUrl($item->action))
                    {
                    $item->action='<?php echo config::$baseUrl;?>' . $item->action;
                    }
                }
            }


        // ändern eines styles
        //<link rel="stylesheet" href="style.css" type="text/css" />
        $domArray=$dom->find("link");

        foreach ($domArray as $item)
            {
            if (isset($item->href))
                {

                // falls kein gültige Url, anfügen der Template Url
                //if (!check::isUrl($item->href))
                //  {
                //if (file::fileExists(config::$projectPath . "/template/" . $item->href, false))
                if (file::fileExists($this->sourcePath . "/" . $item->href, false))
                    {
                    //$link="/data/template/" . $link;
                    /*$item->href='<?php echo config::$baseUrl."' . $this->sourceUrl . '/";?>' . $item->href; */
                    // problem mit anführungszeichen
                    /*$source='<?php echo config::$baseUrl."/data/template_mobile/";?>' . $source;   */
                    /*$item->href='<?php echo config::$baseUrl;?>' . $this->sourceUrl . '/' . $item->href;*/
                    $item->href='[system.base_url]' . $this->sourceUrl . '/' . $item->href;
                    }
                /*$item->href='<?php echo config::$baseUrl."/data/'.$this->compileModus.'/";?>' . $item->href;*/
                //}
                }
            }


        // ändern der script files
        //<script type="text/JavaScript" src="js/map.js"></script>
        $domArray=$dom->find("script");

        foreach ($domArray as $item)
            {
            if (isset($item->src))
                {

                /*$item->src= "hello".'<?php echo config::$baseUrl."/data/template/";?>';//.$item->src;*/
                //$item->src='';

                // falls kein gültige Url, anfügen der Template Url
                //  if (!check::isUrl($item->src))
                //      {
                //$item->src="/data/template/" . $item->src;
                //$item->src="/data/{$this->compileModus}/" . $item->src;
                /*   if (file::fileExists(config::$projectPath . "/" . $this->compileModus . "/" . $item->src, false))
                       {
   
                       /*   $item->src='<?php echo config::$baseUrl;?>/data/' . $this->compileModus . '/' . $item->src;
                         */

                // problem php tags!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                /*$item->src='/data/' . $this->compileModus . '/' . $item->src;
                } */

                if (file::fileExists($this->sourcePath . "/" . $item->src, false))
                    {
                    //$link="/data/template/" . $link;
                    /*$item->src='<?php echo config::$baseUrl."' . $this->sourceUrl . '/";?>' . $item->src; */

                    // dies gibt probleme
                    //$item->src=$this->sourceUrl . "/" . $item->src;

                    // das funktioniert auch nicht --> php tags geben probleme
                    /*$item->src='<?php echo config::$baseUrl;?>' . $this->sourceUrl . '/' . $item->src; */
                    //$item->src='/dddddddddddddddddd' . $this->sourceUrl . '/' . $item->src;
                    $item->src='[system.base_url]' . $this->sourceUrl . '/' . $item->src;
                    }
                }
            }


        // problem, com in script und form sind nicht mehr aktuell
        // Dom basierte Ersetzungen
        /*   $dom=$this->replaceComAttribute($dom);
           //$dom = $this->replaceAttribute($dom);
           $dom=$this->replaceForm($dom);
           $dom=$this->replaceHref($dom);
           $dom=$this->replaceEvent($dom);*/

        $html=$dom->save();
        $dom->clear();
                unset($dom);

        //echo $html;
        //exit;


        // Text basierte Ersetzungen
        $html=$this->replaceShortBracket($html);


        // das brauchts glaube ich nicht mehr (doch für [base_url])
        $html=$this->replacePlaceholder($html);


        // replace Checkbox Value
        /*   $dom=str_get_html($html);  
           
           
           
           $domArray=$dom->find("input[type=checkbox]");
           //$html->find('div[id=hello]', 0)->innertext = 'foo';
           
           foreach ($domArray as $item)
               {
                              
                   $codeChecked='<?php $a = '.$item->value.';if ($a == 1) echo "checked=checked";?>';
                   $item->outertext =re::regexReplace('(<input.*?)/>', $item->outertext, "$1 $codeChecked />");
                         
           
               }
           
            $html=$dom->save();*/


        //$html=$this->replaceField($html);
        // soll


        // JsHeader und CssHeader einf?gen

        $tmp="";


        /* if (sizeof($this->jsHeader) > 0)
             {
             for ($n=0; $n < sizeof($this->jsHeader); $n++)
                 {
 
                 
                 $jsFilename = $this->jsHeader[$n];
                 
                 // erstes Slash abschneiden   
                 //if ($jsFilename[0] == "/")
                 //    $jsFilename=substr($jsFilename, 1);
 
                 $tmp=$tmp . '<script src="' . $this->preIncludePath . $jsFilename . '"></script>';
                 $tmp = $tmp."\r\n";
                 }                             
 
             $this->header=$tmp . $this->header;
             }   */


        // Js Header ersetzen
        $jsHeader="";

        foreach ($this->jsHeader as $headerFilename)
            {

            $jsHeader=$jsHeader . '<script src="<?php echo config::$baseUrl;?>' . $headerFilename . '"></script>'
                . "\r\n";
            }


        // Css Header ersetzen
        $cssHeader="";

        foreach ($this->cssHeader as $headerFilename)
            {

            // jquery libary muss z.T. vor dem Rest des headers geladen sein!!!
            $cssHeader=$cssHeader . '<link rel="stylesheet" href="<?php echo config::$baseUrl;?>'
                . $headerFilename . '" type="text/css" />'
                . "\r\n";
            }

        $this->header=$jsHeader . $cssHeader . $this->header;


        /*     
             $html = str_ireplace("[pre_inclusion_url]", $this->preIncludePath, $html);
             $this->header = str_ireplace("[pre_inclusion_url]", $this->preIncludePath, $this->header);
            */


        // Header ersetzen, falls vorhanden (bei Files vorhanden)
        //$html=str_ireplace("[snapol:snapol_header]", $this->header, $html);

        return $html;
        }


    // php oder html
    private function replaceField($html, $modus = "html") {


    /*  falls es gebraucht wird, muss querycounter eingesetzt werden
    
        // Problem array[0] in einem JavaScript !!!!!!!!!!!!!!!!!!!!!!!!!!
  
          // replace Array
          //$fieldList = regex::getRegexTable("\[([^'\.]*?)\]", $html); f?r was war der Punkt
          $fieldList=regex::getRegexTable("\[([^':\"\$]+?)\]", $html);
          //$queryCounter = $e->data_var;
  
          foreach ($fieldList as $field)
              {
  
              // if (db::tableFieldExist($tableField, $field[$n][1])) {
              //if (in_array($field[1], $tableFieldList)) {
              //echo $field[1];
  
              $fieldArray = explode(".", $field[1]);
  
              //echo $field[1];
              //print_r($fieldArray);
  
              if (sizeof($fieldArray) == 1)
                  {
                  $tableField="";
                  $dbField=$fieldArray[0];
                  }
  
              if (sizeof($fieldArray) == 2)
                  {
                  $tableField=$fieldArray[0];
                  $dbField=$fieldArray[1];
                  }
  
  
  // welche probleme, falls keine abfrage???
  //  if ((db::getValue("SELECT COUNT(1) FROM _table_field WHERE field='$dbField'") > 0) or ($dbField == "id") or ($dbField == "id2")) {
              $queryCounter=$tableField;
  
              if ($modus == "html")
                  $replacePhp='<?php echo $dataquery_' . $queryCounter . '["' . strtolower($dbField) . '"];?>';
  
              if ($modus == "php")
                  $replacePhp='{$dataquery_' . $queryCounter . '["' . strtolower($dbField) . '"]}';
  
  
              //innerhalb von PHP Code
              $replacePhp2='{$dataquery_' . $queryCounter . '["' . strtolower($dbField) . '"]}';
  
              $html=str_ireplace($field[0], $replacePhp, $html);
  
  
              //  }
  
              }   */

    return $html; }


    // replace com attribute (i.e. <div com="mp3" url="">MP3</div>)
    private function replaceCom($dom)
        {

         
            // zur sicherheit, kann sonst zu problemen führen!!!!!!!!!!!!!
            $html=$dom->save();
                $dom->clear();
                unset($dom);
            
            $dom=str_get_html($html);
            
            
            
            
        $jump=false;

        do
            {
            $itemArray=$dom->find("[com]");

            foreach ($itemArray as $item)
                {
                //$item->urs = "yes";


                // Formular Felder auslesen
               /* foreach ($item->find('li,input,p') as $eForm)
                    {
                    $eForm->id="yes3";
                    //echo $eForm->name."  ";

                    }*/


                // erhöhung der queryCounter
                if ((strtolower($item->com)
                    == "data") or (strtolower($item->com) == "data_sortable") or (strtolower($item->com)
                    == "data_outline") or (strtolower($item->com) == "detail_data") or (strtolower($item->com)
                    == "data_checkbox"))
                    {
                    compile_status::$queryCounter++;

                    compile_status::$queryVar="dataquery_" . compile_status::$queryCounter;
                    }

                // Datenvariable zuweisen, falls neue definiert
                if (isset($item->var))
                    {
                    if ($item->var !== "")
                        {
                        compile_status::$queryVar=$item->var;
                        }
                    }

                $this->attributeList=array();


                // get Com Properties
                $comData=component::getCom($item->com);

                if (!$comData)
                    {

                    error::addErrorMessage("com {$item->com} nicht gefunden");
                    }


                //echo $comData['setup'];
                //exit;


                // ausführen des Setup (setup.php File)
                if (trim($comData['setup']) !== "")
                    {
                    $setup=$comData['setup'];
                    $setup=$this->replaceProperty($setup, $item, $comData);
                    eval("?>{$setup}<?php ");
                    }


                // erstellen von Tabellen
                if (trim($comData['db']) !== "")
                    {

                    $xmlConfig=new xml_config();
                    $xmlConfig->xmlString=$comData['db'];
                    $xmlConfig->installXmlConfig();
                    }


                // falls href
                if (($item->tag == "a") or ($item->tag == "form"))
                    {
                    if (trim($comData['php_script']) !== "")
                        {

                        $this->attributeList=array();

                        $fileName=$this->createPhpScript($comData, $item);
                        $urlParameter=$this->getUrlParameter($comData, $item);
                        //$item->href=$fileName . $urlParameter;

                        if ($item->tag == "a")
                            {
                            $item->href='<?php echo config::$baseUrl;?>' . $fileName . $urlParameter;
                            }

                        if ($item->tag == "form")
                            {
                            /*$item->action='<?php echo config::$baseUrl;?>' . $fileName . $urlParameter;*/
                            $item->action=$fileName . $urlParameter;
                            }


                        // Attribute l?schen
                        foreach ($this->attributeList as $attribute)
                            {

                            // Attribute löschen, ausser Attribute href
                            if (($attribute != "href") and ($attribute != "action"))
                                {


                                //$item->$attribute=null;

                                }
                            }
                        }
                    }


                // check


                //$e->innertext=$this->replaceBeginEnd($com, $e, $e->innertext);  */


                // installiert ben?tigte Api's
                //api::checkRquiredApi($comData);


                //$replace=$comData['replace'];


                // ersetzt im kompletten Dokument


                // ersetzen des bestehenden Body
                if (trim($comData['replace']) !== "")
                    {

                    // $item->outertext gibt Probleme!!! Warum????

                    $replace=$comData['replace'];
                    $replace=$this->replaceProperty($replace, $item, $comData);

                    $body=$item->innertext;
                    eval("?>{$replace}<?php ");

                    $item->innertext=$body;
                    }

                // ersetzt Inhalt (body.php)
                if (trim($comData['body']) !== "")
                    {
                    $body=$comData['body'];

                    $body=$this->replaceProperty($body, $item, $comData);

                    $replaceBody=$comData['replace_body'];
                    $replaceBody=$this->replaceProperty($replaceBody, $item, $comData);

                    if ($replaceBody !== "")
                        {
                        eval("?>$replaceBody<?php ");
                        }
                    $item->outertext=$body;
                    }


                // replace inner body (inner_body.php)
                if (trim($comData['inner_body']) !== "")
                    {

                    $body=$comData['inner_body'];
                    $body=$this->replaceProperty($body, $item, $comData);

                    $replaceBody=$comData['replace_body'];
                    $replaceBody=$this->replaceProperty($replaceBody, $item, $comData);

                    if ($replaceBody !== "")
                        {
                        eval("?>$replaceBody<?php ");
                        }

                    $item->innertext=$body;
                    }


                // einfügen von begin/end (begin.php, end.php)
                if (trim($comData['begin']) !== "")
                    {
                    $begin=$comData['begin'];
                    $end=$comData['end'];
                    $begin=$this->replaceProperty($begin, $item, $comData);
                    $end=$this->replaceProperty($end, $item, $comData);

                    $item->innertext=$begin . $item->innertext . $end;
                    }

                $item=$this->replaceOuterBegin($comData, $item);


                // Header einf?gen
                // --> Problem doppelte eintr?ge vermeiden
                $this->setComHeader($comData, $item);

                $item->com=null;

                // Html Attribute löschen
/*foreach (db::getData("_com_property,_com,_property", "com='{$comData['com']}'") as $dataProperty) {
    if (($dataProperty['property_name'] !== "id") and ($dataProperty['property_name'] !== "class") and ($dataProperty['property_name'] !== "action") and ($dataProperty['property_name'] !== "href")) {
         $item->$dataProperty['property_name']=null;      
    } 
} */


                // Property anfügen (nach com löschen, sonst gibts ein problem)
                if (trim($comData['property']) !== "")
                    {
                    if (config::$developerModus)
                        {
                        $url="/com/{$comData['com']}/property.php";
                        }
                    else
                        {
                        $url="/code/property/{$comData['com']}.php";
                        }

                    if (isset($item->property_usergroup))
                        {
                        $propertyLink='<?php if (config::$userData["usergroup_number"] >= '
                            . $item->property_usergroup . ') { ?>';
                        }
                    else
                        {
                        $propertyLink='<?php if ((config::$userData["usergroup_number"] >= config::$defaultPropertyUsergroup) and (config::$editContent))
{ ?>';
                        }

                    $propertyReplace=$propertyLink . '<div id="sortable_' . $item->id . '" class="content_sortable"><p class="edit_button"><a href="<?php echo config::$baseUrl;?>' . $url . '?html_id=' . $item->id . '&content_id=<?php echo config::$contentData["content_id"];?>" style="background-color:#CCC; font-size:14px; border-width:1px; padding:10px">editieren</a> | 
                    <a href="<?php echo config::$baseUrl;?>/system/call/delete_com.php?com_id=' . $item->id . '&content_id=<?php echo config::$contentData["content_id"];?>" style="background-color:#CCC; font-size:14px; border-width:1px; padding:10px"">löschen</a></p>
              <?php }?>' . $item->outertext . $propertyLink . "</div><?php }?>";

                    if (strtolower($item->property_modus) !== "false")
                        {
                        //$item->outertext=   $propertyLink . $item->outertext."</div>";
                        $item->outertext=$propertyReplace;
                        }


                    // Property Modus Attribut löschen
                    $item->property_modus=null;
                    }

                // $item->com=null;

                // ersetzt gesamter Content

                if (trim($comData['replace_content']) !== "")
                    {
                    $replaceContent=trim($comData['replace_content']);
                    $content=$dom->save();

                    eval("?>$replaceContent<?php ");


                    // nachher, sonst ist $item nicht mehr verfügbar
                    $dom->clear();
                    unset($dom);

                    $html=$content;
                    $jump=true;

                    //echo "jump";

                    break;
                    //goto weiter;

                    }


                // Html Attribute löschen
                foreach (db::getData("_com_property,_com,_property", "com='{$comData['com']}'") as $dataProperty)
                    {
                    if (($dataProperty['property_name'] !== "id") and ($dataProperty['property_name'] !== "class")
                        and ($dataProperty['property_name'] !== "action")
                        and ($dataProperty['property_name'] !== "href") and ($dataProperty['property_name'] !== "var"))
                        {
                        $item->$dataProperty['property_name']=null;
                        }
                    }


                // Html Attribute l?schen
/*     foreach ($this->attributeList as $attribute)
         {
         if (($attribute !== "id") and ($attribute !== "name") and ($attribute !== "href") and ($attribute !== "action"))
             {
             $item->$attribute=null;
             }
         }*/

                }


            // Reset Dom Struktur (da sonst Probleme bei Nested Html Tags)

            // Warum nicht bei jedem Durchlauf???? <div com="form_Scaffolding"... braucht auch ein reset!!!
            //$jump=false;  --> gibt problem bei detail_data

            //$jump = false; // wieder löschen

            if ($jump)
                {
                $jump=false;
                //echo "kein reset";
                }
            else
                {
                //echo "  reset ";
                //echo $comData['com'];

                $html=$dom->save();
                $dom->clear();
                unset($dom);
                }

            $dom=str_get_html($html);
            } while (sizeof($itemArray) > 0);

        return $dom;
        }

    function replaceInnerBegin($comData, $item) { }

    function replaceOuterBegin($comData, $item)
        {

        $outerBegin=trim($comData['outer_begin']);
        $outerEnd=$comData['outer_end'];

        if ($outerBegin !== "")
            {
            $item->com=null;

            $outerBegin=$this->replaceProperty($outerBegin, $item, $comData);
            $outerEnd=$this->replaceProperty($outerEnd, $item, $comData);

            $item->outertext=$outerBegin . $item->outertext . $outerEnd;
            }

        return $item;
        }


    /**
    * replace source felder
    * 
    * @param mixed $dom
    */
    private function replaceDetailData($dom)
        {

        $com="visible";
        $domArray=$dom->find("[com]=");

        foreach ($domArray as $item)
            {

            $item->found = "es wurde gefunden";

            $comData=component::getCom($com);
            // Header einf?gen
            // --> Problem doppelte eintr?ge vermeiden
            $this->setComHeader($comData, $item);

            $item->$com=null;
            }
        //}

        return $dom;
        }


    // ersetzt Href Links   (+ form??????????? braucht auch script)
    private function replaceAttribute($dom)
        {

            
         // Reset Dom
        $html=$dom->save();
        $dom->clear();
        unset($dom);
        $dom=str_get_html($html);
            
        
            
            
        //        $domArray=$dom->find($this->htmlElement);

        $comAttribute=array();
        $comAttribute[]="visible";
        $comAttribute[]="usergroup";
        $comAttribute[]="set_focus";
        $comAttribute[]="date_picker";
        $comAttribute[]="if";
        $comAttribute[]="if_exist";
        $comAttribute[]="if_request_exist";
        $comAttribute[]="ck_editor";
        $comAttribute[]="sortable";

        
        $foundCom = false;
        
        
        foreach ($comAttribute as $com)
            {

            
           
                
                
            $domArray = $dom->find("[$com]");

            foreach ($domArray as $item)
                {
                $comData = component::getCom($com);
                // Header einf?gen
                // --> Problem doppelte eintr?ge vermeiden


                // replace Outer Begin
                $item=$this->replaceOuterBegin($comData, $item);

                $this->setComHeader($comData, $item);

                $item->$com=null;
                
                $foundCom = true;
                
                }
                
                
                if ($foundCom) {
                     // Reset Dom
        $html=$dom->save();
        $dom->clear();
        unset($dom);
        $dom=str_get_html($html);
                }
                
                
                
                
            }


        // Reset Dom
        $html=$dom->save();
        $dom->clear();
        unset($dom);
        $dom=str_get_html($html);

        return $dom;
        }


    // ersetzt Komponenten
    //private
    private function replaceBracket($html)
        {
        foreach ($this->arrayCom as $com)
            {

            //      $tag = $dataCom->data['com'];
            $tag = $com['com'];

            $regex=new regex(); // abstand wichtig, sonst werden [com] und [com1] verwechselt
            // problem bei nur Platzhalter
            $regex->getRegexTable("(\[" . $com['com'] . " .*?\])", $html);

            if ($regex->count > 0)
                {
                do
                    {

                    //echo "found".$regex->data[0]."************* HTML: $html";
                    $foundCom=$regex->data[0];
                    $foundComOrginal=$foundCom;

                    // HTMl Zeichen " umwandeln
                    $foundCom=str_replace("&quot;", "\"", $foundCom);

                    //                $this->setComHeader($com['com'], null, $foundCom);
                    //                $body = $this->getBody($com['com'], null, $com['path'], $foundCom);

                    //$fileName    =$this->createPhpScript($com['com'], null, $foundCom);


                    //$body = str_ireplace("[php_script]", $fileName, $body);
                    //$this->header = str_ireplace("[php_script]", $fileName, $this->header);

                    $body="no bracket replacement";

                    $html=str_ireplace($foundComOrginal, $body, $html);

                    //$html = str_ireplace($foundComOrginal, "hier ist ein com", $html);

                    } while ($regex->nextRow());
                }
            } //while ($dataCom->nextRow());

        return $html;
        }


    // ersetzt Komponenten
    private function replacePlaceholder($html)
        {


        /*$dataCom = new data();
        $dataCom->getQuery("SELECT * FROM _com");
  
        do {   */

        $fieldList=regex::getRegexTable("\[([^\']*?)\]", $html);

        //$regex = regex::getRegexTable("(\[" . $com['com'] . "\])", $html);

        foreach ($fieldList as $data)
            {
            //$tag  = $com['com'];

            //$regex=new regex(); // abstand wichtig, sonst werden [com] und [com1] verwechselt
            // problem bei nur Platzhalter


            //if ($regex->count > 0)
            //{
            //do
            //foreach ($regex as $data){

            //echo "found".$regex->data[0]."************* HTML: $html";
            //$foundCom       =$data[0];
            //$foundComOrginal=$foundCom;

            // HTMl Zeichen " umwandeln
            //$foundCom       =str_replace("&quot;", "\"", $foundCom);

            $comData = component::getCom($data[1]);

            if ($comData !== false)
                {


                //$this->setComHeader($com, null, $foundCom);

                //$body=$this->getBody($com, null, $foundCom);


                // compile component
                // $body=$this->replaceCom($body);
                //      $body = $this->replaceCom($body);

                // replace component

                if (trim($comData['body']) !== "")
                    {
                    $html=str_ireplace($data[0], $comData['body'], $html);
                    //$html=str_ireplace($data[0], "COMTEST", $html);

                    }

                //$html = str_ireplace($foundComOrginal, "hier ist ein com", $html);

                } //while ($regex->nextRow());
            //}
            } //while ($dataCom->nextRow());

        return $html;
        }


    // ersetzt Short Bracket's ([user:...] oder [get:...] oder [var:....] oder [error:....])
    // m?gliche Werte f?r $field: short_bracket, php_property oder html_property
    private function replaceShortBracket($html, $modus = "short_bracket") //$replaceFilename)
        {

        // kein schliessende ]
        $regexShortBracket=regex::getRegexTable("(\[([^\]]*?):(.*?)\])", $html);

        foreach ($regexShortBracket as $value)
            {


            //echo "*********************************************************************";
            //print_r($value);
            // ($this->arrayCom as $com)
            //{
            // $tag  = $com['com'];

            //$regex=new regex(); // abstand wichtig, sonst werden [com] und [com1] verwechselt
            // problem bei nur Platzhalter
            //$regex = regex::getRegexTable("(\[" . $com['com'] . ":(.*?)\])", $html);

            /*if ($regex->count > 0)
                {
                do*/

            //            foreach ($regex as $value)    {
            $foundCom = $value[1];
            //$com['com'] = $value[2];


            //$comData = $this->getComData($value[2]);
            $comData=component::getCom($value[2]);


            // Header einf?gen
            //$this->setComHeader($com, $value[3], $com);

            //$filename = $dataCom->data['path']."/short_bracket.php";
            //$filename=$com['path'] . "/$replaceFilename";

            //echo $filename . "  $foundCom";


            //$bracket = db::getValue("SELECT $field FROM _com WHERE com='{$com['com']}'");
            //echo "field $com - $field";

            //$bracket=$this->getComElement($com, $field);

            //echo $bracket;

            //                  echo $value[2];
            //die();

            if ($comData !== false)
                {

                //$bracket = $comData['short_bracket'];
                $bracket=trim($comData[$modus]);

                if ($bracket !== "")
                    {
                    $bracket=str_ireplace("[property]", $value[3], $bracket);


                    //$replace=$this->getComElement($com, "replace");
                    //$replace=$this->replaceProperty($replace, $element, $com);

                    $html=str_ireplace($foundCom, $bracket, $html);
                    }

                /* if (file::fileExists($filename))
                     {
                     $bracket=file::readTextFile($filename);
                     $bracket=str_ireplace("[property]", $regex->data[1], $bracket);
                     $html   =str_ireplace($foundCom, $bracket, $html);
                     }
                 else
                     {
                     //echo "<p>Error: Bracket file $filename not found.</p>";
                     }  */


                // echo "html: $html";

                // $this->setComHeader($com['com'], "")


                // header setzen???????? f?r welche components

                // wieder aktivieren                  } //while ($regex->nextRow());
                //}
                //          } //while ($dataCom->nextRow());  */

                }
            }


        //    $file=new file();

        /*  $dataCom=new data();
          $dataCom->getQuery("SELECT * FROM _com");
  
          do
              {   */
        /* wieder aktivieren  foreach ($this->arrayCom as $com)
              {
              $tag  = $com['com'];
  
              //$regex=new regex(); // abstand wichtig, sonst werden [com] und [com1] verwechselt
              // problem bei nur Platzhalter
              $regex = regex::getRegexTable("(\[" . $com['com'] . ":(.*?)\])", $html);
  
              /*if ($regex->count > 0)
                  {
                  do*/

        /* wieder aktivieren             foreach ($regex as $value)    {
                         $foundCom=$value[1];
     
                         // Header einf?gen
                         $this->setComHeader($com, $value[2], $com);
     
                         //$filename = $dataCom->data['path']."/short_bracket.php";
                         //$filename=$com['path'] . "/$replaceFilename";
     
                         //echo $filename . "  $foundCom";
     
     
                         //$bracket = db::getValue("SELECT $field FROM _com WHERE com='{$com['com']}'"); 
                         //echo "field $com - $field";
     
                         $bracket=$this->getComElement($com, $field);
     
                         //echo $bracket;
     
       //                  echo $value[2];
     //die();
                         
                         $bracket=str_ireplace("[property]", $value[2], $bracket);
                         
                         
     
                         $replace=$this->getComElement($com, "replace");
                         //$replace=$this->replaceProperty($replace, $element, $com);
     
                         $html   =str_ireplace($foundCom, $bracket, $html);
     
     
                         /* if (file::fileExists($filename))
                              {
                              $bracket=file::readTextFile($filename);
                              $bracket=str_ireplace("[property]", $regex->data[1], $bracket);
                              $html   =str_ireplace($foundCom, $bracket, $html);
                              }
                          else
                              {
                              //echo "<p>Error: Bracket file $filename not found.</p>";
                              }  */


        // echo "html: $html";

        // $this->setComHeader($com['com'], "")


        // header setzen???????? f?r welche components

        /* wieder aktivieren                  } //while ($regex->nextRow());
                      //}
                  } //while ($dataCom->nextRow());  */

        return $html;
        }


    /**
    * replace forms replaces with the script.php file
    * 
    * @param mixed $dom
    */

    private function replaceForm($dom)
        {

        $domArray=$dom->find("form[com]");

        foreach ($domArray as $item)
            {
            /*$comAction = "";


            // component kann als action="" oder com_action="" gespeichert werden
            if (isset($item->action))
                $comAction=strtolower(trim($item->action));

            if (isset($item->com_action))
                $comAction=strtolower(trim($item->com_action));  */

            $com = $item->com;

            if ($com !== "")
                {
                $this->attributeList=array();
                $comData=component::getCom($com);

                if ($comData !== false)
                    {

                    $this->setComHeader($comData, $item);

                    $fileName=$this->createPhpScript($comData, $item);

                    // Parameter anh?ngen


                    // PROBLEM URL Parameter
                    $urlParameter="";

                    /*wieder aktivieren
                    $urlParameter = $dataCom["url_parameter"][$n];
                    $urlParameter = $this->replaceComProperty($urlParameter, $e->outertext);
                    */


                    // erstes Slash abschneiden
                    /*if ($fileName[0] == "/")
                        $fileName=substr($fileName, 1);  */

                    //$item->action=$this->preIncludePath . $fileName . $urlParameter; //.$teamUrl; //.$hrefOrginal;
                    /*$item->action='<?php echo config::$baseUrl;?>' . $fileName . $urlParameter;*/
                    /*//$item->action='<?php echo config::$baseUrl;?>' . $fileName . $urlParameter;*/
                    $item->action=$fileName . $urlParameter;


                    // Attribute löschen
                    foreach ($this->attributeList as $attribute)
                        {

                        // Attribute löschen, ausser action Attribute
                        if ($attribute !== "action")
                            {
                            $item->$attribute=null;
                            }
                        }

                    $item->com=null;
                    }
                else
                    {
                    echo "<p>Error: Komponent <b>$com</b> ist nicht gültig.</p>";
                    }
                }
            }

        return $dom;
        }


    // ersetzt Href Links   (+ form??????????? braucht auch script)
    function replaceHref($dom)
        {


        //     $dom->top();
        $itemArray=$dom->find("a[com]");

        foreach ($itemArray as $item)
            {
            $comHref = "";

            /*if (isset($item->href))
                $comHref=$item->href;

            
            
            //strtolower(trim($e->href));

            if (isset($item->com_href))
                $comHref=strtolower(trim($item->com_href));  */

            $com=$item->com;

            $comData=component::getCom($com);

            if ($comData !== false)
                {

                //echo $item->href;
                //print_r($comData);

                //echo "com href $comHref<br>";
                //print_r($comData);


                //if ($comHref !== "")
                //  {
                //if ($comHref == $tag)
                //   {

                $this->attributeList=array();

                $fileName=$this->createPhpScript($comData, $item);
                $urlParameter=$this->getUrlParameter($comData, $item);

                // erstes Slash abschneiden
                /*if ($fileName[0] == "/")
                    $fileName=substr($fileName, 1); */

                //$e->href=$this->preIncludePath . $fileName . $urlParameter;
                //$item->attr("href", $fileName);
                //$item->href=$fileName . $urlParameter;
                $item->href='<?php echo config::$baseUrl;?>' . $fileName . $urlParameter;

                //$item->href=$fileName . $urlParameter;


                // Attribute l?schen
                foreach ($this->attributeList as $attribute)
                    {


                    // Attribute löschen, ausser Attribute href
                    if ($attribute != "href")
                        {
                        $item->$attribute=null;
                        }
                    }

                //$item->com_href=null;
                $item->com=null;
                }
            else
                {

                // Com wurde nicht gefunden
                echo "<p>Fehler: Component <b>$com</b> wurde nicht gefunden.</p>";
                exit;
                }
            }
        // }
        //}

        return $dom;
        }


    /**
    * replace JavaScript Events
    * 
    * @param mixed $dom
    */
    private function replaceEvent($dom)
        {


        // verschiedene Events definieren
        $eventList=array();
        $eventList[]="mouseover";
        $eventList[]="click";
        $eventList[]="dblclick";
        $eventList[]="change";

        foreach ($eventList as $event)
            {

            //foreach ($dom->find("[click]") as $item)
            //{

            foreach ($dom->find("[$event]") as $item)
                {
                //for ($n=0; $n < sizeof($eventList); $n++)
                //  {
                //if (isset($item->$eventList[$n]))
                //  {
                // if ($item->$eventList[$n] !== "")
                //   {

                $this->attributeList = null;

                //$comData=$this->getComData($item->$eventList[$n]);
                //$comData=component::getCom($item->$eventList[$n]);
                $comData=component::getCom($item->$event);

                //$this->setComHeader($e->$eventList[$n], "/com/" . $e->$eventList[$n], $e, null);
                //$comObject=array();

                //$comObject['com']     =$e->$eventList[$n];
                //$comObject['com_path']="/com/" . $e->$eventList[$n];

                $this->setComHeader($comData, $item);

                //$e                =$this->createJsScript($eventList[$n], "/com/" . $e->$eventList[$n], $e);
                //$item=$this->createJsScript($eventList[$n], $comData, $item);
                $item=$this->createJsScript($event, $comData, $item);


                // falls Link, Spezialzeichen einfügen
                if ($item->tag == "a")
                    {
                    $item->href="#";
                    }


                // Html Attribute l?schen
                /*foreach ($this->attributeList as $attribute) {
                    $item->$attribute = null;
                } */
                //$item->$eventList[$n]=null;
                $item->$event=null;
                }
            //  }

            }


        /*     if(isset($e->click)) { 
            
            echo "found";  
                $e = $this->createJsScript($eventList[$n], $e);
                $e->$eventList[$n] = null;
                }
            
        
            
            
/*        if(isset($e->mouseover)) {   
             //echo "found";
            $e = $this->createJsScript("mouseover", $e);
            $e->mouseover = null;
            
        }
        
        
         //Menu
    /*    if(isset($e->click)) {   
         
// function getComponent
          //  $com = $e->com;
             
             //echo "COM: ".$com;
             $com = $e->click;
             $e->click = null;
             
           /*  $outertextOrginal =  $e->outertext;
             
             //$comFileName = "/com/$menu/"
             
         $str = db::getValue("SELECT php FROM _com WHERE com = '$com'");
         $str = $this->replaceComProperty($str, $outertextOrginal);        */


        // Header einf?gen
        // --> Problem doppelte eintr?ge vermeiden
        /*$header = db::getValue("SELECT header FROM _com WHERE command = '$com'");
        $header = $this->replaceComProperty($header, $e->outertext);  
        $this->header = $this->header.$header;   */


        /*        $e->href = "#";
       
               
           //    $file = new file();
               
               
               //js script
               $scriptFilename = "/com/$com/script.js";
               
               if (file::fileExists($scriptFilename)) {
                   $script = file::readTextFile($scriptFilename);
                   
                   
                   $script = $this->replaceProperty2($script, $e);
                   
                   $functionName = "func_".rand(0,10000)."()";
                   $script = "function $functionName { \r\n $script \r\n }";
                   
                   
                   $fileName = "/code/script/script_".rand(0,10000).".php";     
                   if(isset($e->filename)) { 
                       $fileName = "/code/script/".$e->filename;   // problem, falls standalone modus
                       $e->filename = null;    
                   }   
               
                   file::createTextFile($fileName, $script);               
               
                   // script im Header anf?gen
                   $this->header = $this->header.'<script src="'.$fileName.'" language="javascript"></script>';
                   $this->setComHeader($com, $e->outertext); */


        //$script = $this->replaceProperty($script, $outertextOrginal);
        // Header einf?gen
        // $this->setComHeader($tag,  $regex->data[1]);

        /*      $e->onclick = "$functionName; return false;";
              //$script;
          
          } */


        // php script
        /*    $phpScriptFilename = "/com/$com/script.php";  
            
            if ($file->fileExists($phpScriptFilename)) {
                $script = $file->readTextFile($phpScriptFilename);
                
                //echo $script;
                //echo $outertextOrginal;
                
                
                $script = $this->replaceComProperty($script, $outertextOrginal);    
                //$e->onclick = $script;
                $fileName = "/code/script/script_".rand(0,10000).".php";     
                if(isset($e->filename)) { 
                    $fileName = "/code/script/".$e->filename;   // problem, falls standalone modus
                    $e->filename = null;    
                }   
            
            
                $file->createTextFile($fileName, $script);
            
            }    */


        // header
        /*     $headerFilename = "/com/$com/header.html";
             
             if ($file->fileExists($headerFilename)) {
                 $header = $file->readTextFile($headerFilename);
                 $header = $this->replaceComProperty($header, $outertextOrginal); 
                 $this->header = $this->header.$header;    
             
             }  */


        /* $str = trim($str);
         
         //
         if ($str !== "")
             $e->outertext = $str;  */

        //  }
        // }

        return $dom;
        }


    // setzt den Header f?r einen Komponenten
    private function setComHeader($comData, $item)
        {

        // Controller anhängen
        $controllerTmp=$comData['controller'];
        $controllerTmp=$this->replaceProperty($controllerTmp, $item, $comData);
        $this->controller=$this->controller . $controllerTmp;


        // Header anhängen
        $headerTmp=$comData['header'];
        $headerTmp=$this->replaceProperty($headerTmp, $item, $comData);
        $this->header=$this->header . $headerTmp;

        // js_header.txt auslesen
        //$jsHeader    =$this->getComElement($comObject, "js_header");
        $jsHeader=$comData['js_header']; //$this->getComElement($comObject, "js_header");
        $jsHeader=explode("\n", $jsHeader);

        if (sizeof($jsHeader) > 0)
            {
            for ($n=0; $n < sizeof($jsHeader); $n++)
                {
                $jsHeader[$n] = trim($jsHeader[$n]);

                if ($jsHeader[$n] !== "")
                    {
                    if (!in_array($jsHeader[$n], $this->jsHeader))
                        $this->jsHeader[]=$jsHeader[$n];
                    }
                }
            }


        // css_header.txt auslesen
        //$jsHeader=$this->getComElement($comObject, "css_header");
        $jsHeader=$comData['css_header'];
        $jsHeader=explode("\n", $jsHeader);

        if (sizeof($jsHeader) > 0)
            {
            for ($n=0; $n < sizeof($jsHeader); $n++)
                {
                $jsHeader[$n] = trim($jsHeader[$n]);

                if ($jsHeader[$n] !== "")
                    {
                    if (!in_array($jsHeader[$n], $this->cssHeader))
                        $this->cssHeader[]=$jsHeader[$n];
                    }
                }
            }
        }


    // read body file of a component       //$foundCom
    private function getBody($comObject, $attribute)
        {
        if (file::fileExists($comObject['com_path'] . "/function.php"))
            {
            //if (file::fileExists($comPath."/function.js")) {
            //$script      =$this->getComElement($com, $comPath, "js_script");
            //$body=$this->getComElement($com, $comPath, "js_function");
            $body=$this->getComElement($comObject, "php_function");

            if (file::fileExists($comObject['com_path'] . "/script.php"))
                {
                $phpScript=$this->getComElement($comObject, "php_script");

                if ($phpScript !== "")
                    $phpFilename=$this->createPhpScript($comObject, $element);


                // falls ein php script aufgerufen wird
                $body=str_ireplace("[php_script]", $phpFilename, $body);
                }
            }
        else
            {
            $body=$this->getComElement($comObject, "body");
            }

        $body=$this->replaceProperty($body, $attribute, $comObject); //$foundCom);

        $body=trim($body);
        return $body;
        }

    function replaceBeginEnd($comObject, $element, $html)
        {

        $begin=$this->getComElement($comObject, "begin");
        $begin=$this->replaceProperty($begin, $element, $comObject);

        $replaceBegin=$this->getComElement($comObject, "replace_begin");

        $replaceBegin=$this->replaceProperty($replaceBegin, $element, $comObject);
        $timer->stopTimer();

        if ($replaceBegin !== "")
            {
            $timer=new timer_com("eval replace begin");
            /*  eval("?>$replaceBegin<?php ");*/
            $timer->stopTimer();
            }


        //$end = db::getValue("SELECT end FROM _com WHERE com='$com'");
        $timer=new timer_com("end");
        $end=$this->getComElement($comObject, "end");
        $end=$this->replaceProperty($end, $element, $comObject);
        $timer->stopTimer();

        $e=$element;

        //$replace = db::getValue("SELECT `replace` FROM _com WHERE com='$com'");
        $replace=$this->getComElement($comObject, "replace");
        $replace=$this->replaceProperty($replace, $element, $comObject);


        //echo "$com<br>";
        $timer=new timer_com("eval replace");
        eval("?>$replace<?php ");
        $timer->stopTimer();

        $html=$begin . $html . $end;


        // Outer begin

        echo "<p>*********</p>";
        return $html;
        }

    //  function replaceOuterBeginEnd($comObject, $element, $html) {
    /*     $begin=$this->getComElement($com, $comPath, "outer_begin");
         $begin=$this->replaceProperty($begin, $element);
         $replaceBegin=$this->getComElement($com, $comPath, "replace_outer_begin");
 
         if ($replaceBegin !== "")
             eval ("?>$replaceBegin<?php ");
 
         //$end = db::getValue("SELECT end FROM _com WHERE com='$com'");     
         $end    =$this->getComElement($com, $comPath, "outer_end");
         $end    =$this->replaceProperty($end, $element);
 
         $e      =$element;
 
         //$replace = db::getValue("SELECT `replace` FROM _com WHERE com='$com'");    
         $replace=$this->getComElement($com, $comPath, "replace");
 
         //echo "$com<br>";
 
         eval ("?>$replace<?php ");
 
         $html   =$begin . $html . $end; */


    // Outer begin

    //  return $html; }


    // gibts es ein begin.php und end.php File
    /*  $beginFilename="/com/{$com['com']}/begin.php";

      if (file::fileExists($beginFilename))
          {
          $html           =file::readTextFile($beginFilename);
          //                        $tmp         =$this->replaceProperty($tmp, $e->outertext);
          $html           =$this->replaceProperty($html, $e);


          // replace.php (ersetzt
          $replaceFilename="/com/{$com['com']}/replace_begin.php";

          if (file::fileExists($replaceFilename))
              {
              //echo " $html  found";
              global $rootDir;
              //$html        =$e->innertext;
              require($rootDir . $replaceFilename);
              //echo $html;
              //$e->innertext=$html;
              }

          $e->innertext=$html . $e->innertext;
          }

      $endFilename="/com/{$com['com']}/end.php";

      if (file::fileExists($endFilename))
          {
          $tmp         =file::readTextFile($endFilename);
          //$tmp         =$this->replaceProperty($tmp, $e->outertext);
          $tmp         =$this->replaceProperty($tmp, $e);
          $e->innertext=$e->innertext . $tmp;
          }


      //echo "found $tag - $n,";    
      // OUTER REPLACE 
      // gibts es ein outer_begin.php und outer_end.php File
      $beginFilename="/com/{$com['com']}/outer_begin.php";

      if (file::fileExists($beginFilename))
          {
          $tmp         =file::readTextFile($beginFilename);
          //$tmp         =$this->replaceProperty($tmp, $e->outertext);
          $tmp         =$this->replaceProperty($tmp, $e);


          //echo $com['com'];
          $e->outertext=$tmp . $e->outertext;
          }


      // replace.php (ersetzt
      $replaceFilename="/com/{$com['com']}/replace.php";

      if (file::fileExists($replaceFilename))
          {
          global $rootDir;
          $html=$e->innertext;
          require($rootDir . $replaceFilename);
          $e->innertext=$html;
          }  */


    // setzt den Header f?r einen Komponenten
    //private function getComUrlParameter($com, $foundCom)
    private function getUrlParameter($comData, $item) //element, $foundCom = "")
        {
        //$file                =new file();
        //$urlParameterFilename="/com/$com/url_parameter.txt";
        //      if (!$file->fileExists($bodyFilename))
        //       $bodyFilename = "/com/$com/body.php";

        // echo $bodyFilename;
        $urlParameter="";
        //$urlParameter = db::getValue("SELECT url_parameter FROM _com WHERE com='$com'");
        //$urlParameter=$this->getComElement($comObject, "url_parameter");
        $urlParameter=$comData['url_parameter'];
        $urlParameter=$this->replaceProperty($urlParameter, $item, $comData);

        // falls group modus, mygroup anh?ngen
        global $groupModus;

        if ($groupModus)
            {
            $urlParameter=$urlParameter . "&mygroup=<?php echo \$_REQUEST['mygroup']; ?>";

            //$data['_mygroup'] = $mygroup;
            }


        /* if (file::fileExists($urlParameterFilename))
             {
             $urlParameter=file::readTextFile($urlParameterFilename);
 
             //echo $urlParameter;
             //$urlParameter=$this->replaceProperty($urlParameter, $foundCom, false);
             $body = db::getValue("SELECT body FROM _com WHERE com='$com'");   
             $urlParameter=$this->replaceProperty($urlParameter, $element, $foundCom, false);
             // echo $urlParameter;       
 
             // falls group modus, mygroup anh?ngen
             global $groupModus;
 
             if ($groupModus)
                 {
                 $urlParameter=$urlParameter . "&mygroup=<?php echo \$_REQUEST['mygroup']; ?>";
 
                 //$data['_mygroup'] = $mygroup;
                 }
             //}
 
             }*/

        return $urlParameter;
        }


    /**
    * erstellt das com script (script.php)
    * 
    * @param mixed $comData
    * @param mixed $item
    */
    private function createPhpScript($comData, $item)
        {

        $script=$comData['php_script'];

        // replace System Path
        $script=str_ireplace("[system_path]", $this->systemPath, $script);

        $script=$this->replaceProperty($script, $item, $comData); // $foundCom);


        //$replacePhpScript=$this->getComElement($com, "replace_php_script");

        if ($comData['replace_php_script'] !== "")
            {

            $replacePhpScript=$comData['replace_php_script'];
            $replacePhpScript=$this->replaceProperty($replacePhpScript, $item, $comData);


            // die Variable $script enth?lt das zu bearbeitende PHP Script
            eval("?>$replacePhpScript<?php ");
            }


        // Filename des Script auslesen
        $this->phpScriptCounter++;


        //$filename="{$this->phpScriptPath}/" . $this->codeFilename .  "_" . $this->phpScriptCounter .".php";

        $tmp=$this->codeFilename;
        $tmp=file::getFilename($tmp);
        $tmp=str_ireplace(".php", "", $tmp);
        $filename=$tmp . "_" . $this->phpScriptCounter . ".php";

        // falls das Attribute script_filename vorhanden ist
        if (isset($item->script_filename))
            {
            //          "{$this->phpScriptPath}"

            ///code/php_script
            $filename=$item->script_filename; // problem, falls standalone modus
            $item->script_filename=null;
            }

        //    $filename="/code/php_script/" . $tmp ;
        $phpScriptFilename=config::$basePath . config::$codePath . "/php_script/" . $filename;
        $webFilename=config::$codePath . "/php_script/" . $filename;
        //config::$baseUrl

        file::createTextFile($phpScriptFilename, $script, false);


        // relative filename
        //$filename = $this->getRelativeUrl($filename);

        return $webFilename;
        }

    private function createJsScript($event, $comData, $item)
        {

        // ist ein PHP Script vorhanden
        $phpFilename="";
        $phpScript=$comData['php_script'];

        if ($phpScript !== "")
            {
            $phpFilename=$this->createPhpScript($comData, $item);
            }


        // ist ein php script file vorhanden
        /*   $phpScriptFilename="/com/$com/script.php";
           $codePhpScriptFilename="";
   
           if (file::fileExists($phpScriptFilename))
               {
               $codePhpScriptFilename=$this->createPhpScript($com, $element);
               }
   
           $scriptFilename="/com/$com/script.js";
   
           if (file::fileExists($scriptFilename))
               {
               $script      =file::readTextFile($scriptFilename);*/


        //$script = db::getValue("SELECT js_script FROM _com WHERE com='$com'");

        //if (file::fileExists($comObject['com_path'] . "/script.js"))
        //    {
        //    $script=$this->getComElement($comObject, "js_script");
        $script=$comData['js_script'];
// $this->getComElement($comObject, "js_script");
//    }
// else
//   {
//   $script=$this->getComElement($comObject, "js_function");


// ACHTUNG dies wird gebraucht, falls function.js und nicht script.js verwendet wird!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// $script="function  [function_name](){ " . $script . "}";


// }


//$script  =$this->replaceProperty($script, $element, $foundCom);


// falls ein php script aufgerufen wird
        $script=str_ireplace("[php_script]", $phpFilename, $script);
        // --------> WIEDER AKTIVIEREN

        $script=$this->replaceProperty($script, $item, $comData);

        $functionName="func_" . rand(0, 10000);
        //$script = "function $functionName() { \r\n $script \r\n }";

        $script=str_ireplace("[function_name]", $functionName, $script);

        //$fileName    ="/code/script/script_" . rand(0, 10000) . ".php";

        /*if (isset($element->filename))
            {
            $fileName   ="/code/script/" . $element->filename; // problem, falls standalone modus
            $e->filename=null;
            }  */

        //file::createTextFile($fileName, $script);

        // Dateiendung muss php sein, da sonst Php Komponenten nicht ausgef?hrt werden k?nnen
        $this->jsScriptCounter++;


        //$this->phpScriptCounter++;


        //$filename="{$this->phpScriptPath}/" . $this->codeFilename .  "_" . $this->phpScriptCounter .".php";

        $tmp=$this->codeFilename;
        $tmp=file::getFilename($tmp);
        $tmp=str_ireplace(".php", "", $tmp);
        $filename=config::$codePath . "/js_script/" . $tmp . "_" . $this->jsScriptCounter . ".php";

        /*$filename="/code/js_script/" . $this->compileTable . "_" . $this->compileField . "_" . $this->compileId . "_"
            . $this->jsScriptCounter . ".php"; */


        // sollte in script_filename ge?ndert werden
        if (isset($item->script_filename))
            {
            $filename=config::$codePath . "/js_script/" . $element->script_filename; // problem, falls standalone modus
            $item->script_filename=null;
            }

        file::createTextFile(config::$basePath . $filename, $script, false);


        // script im Header anf?gen
        $this->header=$this->header . '<script src="<?php echo config::$baseUrl;?>' . $filename
            . '" language="javascript"></script>';
        $this->setComHeader($comData, $item);


        //return "$functionName; return false;";
        /*        }
            else
                {
                echo "Error: Kein Event File f?r $com gefunden";
                } */

        /*  $functionParameterFilename="/com/$com/function_parameter.txt";
          $functionParameter="";
  
          if (file::fileExists($functionParameterFilename))
              {
              $functionParameter=file::readTextFile($functionParameterFilename);
  
              //echo $functionParameter;
  
              $functionParameter=$this->replaceProperty($functionParameter, $element);
  
              //echo "************".$functionParameter;
  
              } */

        $functionParameter=$comData['function_parameter'];
        $functionParameter=$this->replaceProperty($functionParameter, $item, $comData);


        // Java Script spezifisches on anf?gen
        $event="on$event";


        // return false muss vorhanden sein!!!!
        $item->$event="$functionName($functionParameter); return false;";
        //$item->$event="$functionName($functionParameter);";

        return $item;

        //$script = $this->replaceProperty($script, $outertextOrginal);
        // Header einf?gen
        // $this->setComHeader($tag,  $regex->data[1]);


        //$script;

        }

    // sollte replaceAttribute heissen, oder???
    private function replaceProperty($html, $item, $comData)
        {

        // to do--> in das gleiche regex verpacken

        //        $html=str_ireplace("[query_counter]", "", $html);
        $html=str_ireplace("[query_counter]", compile_status::$queryCounter, $html);
        $html=str_ireplace("[query_var]", compile_status::$queryVar, $html);


        // query counter ersetzen, falls attribut data_var vorhanden, sonst z?hler
        /* if (isset($htmlElement->data_var))
             {
             $html=str_ireplace("[query_counter]", $htmlElement->data_var, $html);
             }   */

        $phpData=re::getRegexArray("\[html_property:(.*?)\]", $html);

        foreach ($phpData as $parameterKey)
            {
            //$parameterValue = $htmlElement->$parameterKey;
            //$parameterValue = $dom->attr($parameterKey);

            $this->attributeList[] = $parameterKey;


            /*  $parameterValue = "";
              if (isset($attribute[$parameterKey]))  
             $parameterValue = $attribute[$parameterKey];*/
            $parameterValue=$item->$parameterKey;

            $parameterValue=$this->replaceShortBracket($parameterValue, "html_property");
            $parameterValue=$this->replacePlaceholder($parameterValue);

            $parameterValue=$this->replaceField($parameterValue, "html");

            $html=str_ireplace("[html_property:$parameterKey]", $parameterValue, $html);
            }

        $phpData=re::getRegexArray("\[php_property:(.*?)\]", $html);

        // echo $html;

        foreach ($phpData as $parameterKey)
            {
            //$parameterValue = $htmlElement->$parameterKey;
            //$parameterValue = $dom->attr($parameterKey);

            //print_r($attribute);
            //print_r(array_keys($attribute));
            //echo "key=$parameterKey={$attribute[$parameterKey]}";
            $this->attributeList[] = $parameterKey;


            //   echo $parameterKey." = ";


            /*  $parameterValue ="";
             if (isset($attribute[$parameterKey]))
              $parameterValue = $attribute[$parameterKey];   */
            $parameterValue=$item->$parameterKey;

            $parameterValue=$this->replaceShortBracket($parameterValue, "php_property");
            $parameterValue=$this->replacePlaceholder($parameterValue);

            $parameterValue=$this->replaceField($parameterValue, "php");


            //echo $parameterValue;

            $parameterValue=str_replace('<?php echo ', '{', $parameterValue);
            $parameterValue=str_replace(';?>', '}', $parameterValue);
            $parameterValue=str_replace('; ?>', '}', $parameterValue);

            $html=str_ireplace("[php_property:$parameterKey]", $parameterValue, $html);

            //   echo $parameterValue;

            }

        //  echo $html;

        // exit;


        // zus?tzliche Php Files
        $phpData=re::getRegexArray("\[php:(.*?)\]", $html);

        foreach ($phpData as $value)
            {
            if (config::$developerModus)
                {
                $filename=$comData['path'] . "/php/$value";
                $script=file::readTextFile($filename, false);
                }
            else
                {
                $comId=db::getValue("SELECT id FROM _com WHERE com='{$comData['com']}'");
                $script=db::getValue("SELECT script FROM _com_script WHERE __com='{$comId}' AND filename='{$value}'");
                }

            $script=str_ireplace("[system_path]", $this->systemPath, $script);

            $script=$this->replaceProperty($script, $item, $comData);

            $tmp=$this->codeFilename;
            $tmp=file::getFilename($tmp);
            $tmp=str_ireplace(".php", "_", $tmp);
            //$filename=$tmp . "_" . $this->phpScriptCounter . ".php";

            $this->phpScriptCounter++;
            $filename=config::$codePath . "/php_script/" . $tmp . $this->compileTable . "_" . $this->compileField . "_"
                . $this->compileId . "_"
                . $this->phpScriptCounter . ".php";

            file::createTextFile($filename, $script, true);


            // Base Url einfügen (wird z.B. für Ajax etc. verwendet)
            $filename=config::$baseUrl . $filename;

            $html=str_ireplace("[php:$value]", $filename, $html);
            }

        $html=trim($html);

        return $html;
        }

    private function cleanCode($text)
        {
        $text=str_replace('<?php echo ', '{', $text);

        $text=str_replace(';?>', '}', $text);

        $text=str_replace('; ?>', '}', $text);

        return $text;
        }


    // innerhalb von Variablen
    function compileVariable($html)
        {


        // replace variable
        /*  $html=preg_replace("/\[var:(.*?)\]/is", '<?php echo \$$1;?>', $html);   
         
           
              // replace session object
          $html=preg_replace("/\[session:(.*?)\]/is", '<?php echo \$_SESSION[\'$1\'];?>', $html);   
         // vor replacedata 
           
           
         //  $html = $this->replaceUserData($html);
           $html = $this->replaceCmsData($html);     
           
           
               // replace detail fields --> wird m?hsam f?r clean code
      
      /*     $html=preg_replace("/\[detail:(.*?)\]/is", '<?php echo $lineform[\'$1\'];?>', $html); */

        // query objekt einf?gen


        //echo $html;
        $html=$this->replaceParameter($html);
        $html=$this->replaceComPlaceholder($html);

        $html=$this->replaceComShortBracket($html);


        // replace variable
        /*   $html=preg_replace("/\[var:(.*?)\]/is", '<?php echo \$$1;?>', $html);   
          
          
           
           // replace session object
           $html=preg_replace("/\[session:(.*?)\]/is", '<?php echo \$_SESSION[\'$1\'];?>', $html);   
          
           
           
           // replace cookie object
           $html=preg_replace("/\[cookie:(.*?)\]/is", '<?php echo \$_COOKIE[\'$1\'];?>', $html);  */


        // replace placeholder ([http_useragent], [host] etc.)
        /*      $dataCom = sqlQuery("SELECT * FROM _com");
              
              
              // muss ersetzt werden
              for ($n=0; $n<sizeof($dataCom['id']); $n++) {
                   $html = str_ireplace("[".$dataCom["com"][$n]."]", $dataCom["php"][$n], $html);
              }  */

        return $html;
        }


    // muss anders heissen --> verwirrung mit html element
    function getComElement2($comObject, $element)
        {
        if ($this->developerModus)
            {
            $comPath=$comObject['com_path'];

            $filename="$comPath/$element.php";

            if ($element == "url_parameter")
                $filename="$comPath/url_parameter.txt";

            if ($element == "function_parameter")
                $filename="$comPath/function_parameter.txt";

            if ($element == "js_header")
                $filename="$comPath/js_header.txt";

            if ($element == "css_header")
                $filename="$comPath/css_header.txt";

            if ($element == "php_script")
                $filename="$comPath/script.php";

            if ($element == "js_script")
                $filename="$comPath/script.js";

            if ($element == "js_function")
                $filename="$comPath/function.js";

            if ($element == "php_function")
                $filename="$comPath/body.php";


            //echo "<p>not found $filename</p>";

            $html="";

            if (file::fileExists($filename))
                {
                $html=file::readTextFile($filename);
                }
            else
                {
                //echo "<p>not found $filename</p>";

                }
            }
        else
            {
            $html=db::getValue("SELECT `$element` FROM _com WHERE com='$com'");
            }

        return $html;
        }


    // muss anders heissen --> verwirrung mit html element
    /*  function getComElement($comObject, $element)
          {
          if ($this->developerModus)
              {
              $filename="{$comObject['com_path']}/$element.php";
  
              if ($element == "url_parameter")
                  $filename="{$comObject['com_path']}/url_parameter.txt";
  
              if ($element == "function_parameter")
                  $filename="{$comObject['com_path']}/function_parameter.txt";
  
              if ($element == "js_header")
                  $filename="{$comObject['com_path']}/js_header.txt";
  
              if ($element == "css_header")
                  $filename="{$comObject['com_path']}/css_header.txt";
  
              if ($element == "php_script")
                  $filename="{$comObject['com_path']}/script.php";
  
              if ($element == "js_script")
                  $filename="{$comObject['com_path']}/script.js";
  
              if ($element == "js_function")
                  $filename="{$comObject['com_path']}/function.js";
  
              if ($element == "php_function")
                  $filename="{$comObject['com_path']}/body.php";
  
  
              //echo "<p>not found $filename</p>";
  
              $html="";
  
              if (file::fileExists($filename))
                  {
                  $html=file::readTextFile($filename);
                  }
              else
                  {
                  //echo "<p>not found $filename</p>";
  
                  }
              }
          else
              {
              $html=db::getValue("SELECT `$element` FROM _com WHERE com='{$comObject['com']}'");
              }
  
          return $html;
          }  */

    function replaceMailAdress($dom)
        {

        /*
        <script language="JavaScript" type="text/JavaScript">
          a="urs.lang";
          b="gmail.com";
          document.write("<a href=\"mailto:"+a+"@"+b+"\">"+a+"@"+b+"</a>");
        </script>*/


        // --> ersetzt nur Best Practice

        // problem mit $dataquery["field"]
        // kann verhindert werden mit (.*?)\">  --> dies gibt aber Probleme, falls dort eine Klasse angegeben wurde
        // lösung: dom

        //$dom=str_get_html($buffer);


        // ändern der Form's
        $domArray=$dom->find("a");

        foreach ($domArray as $item)
            {
            if (isset($item->href))
                {

                // falls kein gültige Url, anfügen der Template Url
                /* if (!check::isUrl($item->action))
                     {
                     $item->action='<?php echo config::$baseUrl;?>' . $item->action;
                     }
                 }*/


                /*       $re="/<a href=\"mailto:(.*?)\".*?>(.*?)<\/a>/is";  */
                //$re="/mailto:(.*?)/is";

                if (strstr($item->href, "mailto:") !== false)
                    {


                    //preg_match_all($re, $item->href, $out2, PREG_SET_ORDER);

                    /* for ($n=0; $n < sizeof($out2); $n++)
                         {
                         $inhaltReplace = $out2[$n][0];
                         $mailAdress=trim($out2[$n][1]);
                         $mailName=trim($out2[$n][2]);*/


// nur ersetzen, falls $mailAdress eine g?ltige Mail Adresse ist (sonst gibt es probleme bei datenfelder)

//$mailAdress=$item->href;
                    $mailAdress=str_ireplace("mailto:", "", $item->href);

                    // falls es bereits eine eMail Adresse ist
                    if (check::isEmail($mailAdress))
                        {
                        $mail=explode("@", $mailAdress);

                        //print_r($mail);


                        // falls mailName der eMail Adresse entspricht
                        //if ($mailAdress == $mailName)
                        $mailName="\"+a+\"@\"+b+\"";


                        // ?bernahmen von class id etc.

                        $code="<script language=\"JavaScript\" type=\"text/JavaScript\">a=\"" . $mail[0] . "\";b=\""
                            . $mail[1] . "\";document.write(\"<a href=mailto:\"+a+\"@\"+b+\">" . $mailName
                            . "</a>\");</script>";

                        //$buffer = "email".$javaScript;

                        //$buffer=str_replace($inhaltReplace, $javaScript, $buffer);
                        }
                    else
                        {

                        // falls keine g?ltige eMail Adresse, vermutlich ist es dann tabellen feld

                        //$mailAdress=str_ireplace("mailto:", "", $mailAdress);
                        $mailAdress=$this->cleanCode($mailAdress);

                        $mailAdress=str_replace("{", "", $mailAdress);
                        $mailAdress=str_replace("}", "", $mailAdress);
                        $inhaltReplace="";

                        //echo $mailAdress;
                        //exit;
                        // $mailAdress = '"@"';
                        $code='<?php $mail=explode("@", ' . $mailAdress . ');if (sizeof($mail)>1) { 
          echo "<script language=\"JavaScript\" type=\"text/JavaScript\">a=\"" . $mail[0] . "\";b=\"" . $mail[1]
            . "\";document.write(\"<a href=mailto:\"+a+\"@\"+b+\">\"+a+\"@\"+b+\"</a>\");</script>";} else { echo  
            '
                            . $mailAdress . '; }?>';

                        // abfrage, ob eine klasse bestimmt wurde
                        // if isset $item->class


                        //   echo $mailAdress;
                        //$buffer=str_replace($inhaltReplace, $phpCode, $buffer);
                        }

                    //$item->href = $code;
                    $item->outertext=$code;
                    }
                }
            }

        //$buffer=$dom->save();

        //return $buffer;
        return $dom;
        }


    /**
    * gibt den include Pfad an
    * 
    */
    function getRelativeUrl($url)
        {

        //       $count            =substr_count($fileNameTo, '/') - 1;
        $count=substr_count($this->pageUrl, '/') - 1;


        //$frameworkFilename = "";
        //global $frameworkFilename;
        //$frameworkFilename="";
        $relativeUrl="";


        //echo "count $count";

        for ($n=0; $n < $count; $n++)
            {
            $relativeUrl=$relativeUrl . "../";
            }

        //$preIncludePath = $frameworkFilename;

        $relativeUrl=$relativeUrl . $url;
        //$frameworkFilename=$frameworkFilename . "system/framework.php";
        //$frameworkFilename="{$this->systemPath}system/framework.php";

        return $relativeUrl;
        }


    /**
    * gibt den include Pfad an
    * 
    */
    function getFramworkFilename()
        {

        //       $count            =substr_count($fileNameTo, '/') - 1;
        $count=substr_count($this->pageUrl, '/') - 1;


        //$frameworkFilename = "";
        //global $frameworkFilename;
        $frameworkFilename="";


        //echo "count $count";

        for ($n=0; $n < $count; $n++)
            {
            $frameworkFilename=$frameworkFilename . "../";
            }

        //$preIncludePath = $frameworkFilename;

        $frameworkFilename=$frameworkFilename . "system/framework.php";
        //$frameworkFilename="{$this->systemPath}system/framework.php";

        }
    }
?>